import 'package:flutter/material.dart';
import 'package:flutter_enjoy_plus/apis/user.dart';
import 'package:flutter_enjoy_plus/utils/Emitter.dart';
import 'package:flutter_enjoy_plus/utils/TokenManageer.dart';
import 'package:flutter_enjoy_plus/utils/toast.dart';

class MinePage extends StatefulWidget {
  const MinePage({super.key, required this.updateIndexFn});
  // 定义函数类型
  final Function(int) updateIndexFn;

  @override
  State<MinePage> createState() => _MinePageState();
}

class _MinePageState extends State<MinePage> {
  // 菜单数据
  final List menuList = [
    {
      "title": "我的房屋",
      "icon": "assets/images/house_profile_icon@2x.png",
    },
    {
      "title": "我的报修",
      "icon": "assets/images/repair_profile_icon@2x.png",
    },
    {
      "title": "访客记录",
      "icon": "assets/images/visitor_profile_icon@2x.png",
    }
  ];

  // 用户信息
  Map<String, dynamic> userInfo = {
    'id': '',
    'avatar': '',
    'nickName': '',
  };

  /// 获取用户信息
  _getUserInfo() async {
    final res = await UserApi.getUserInfo();
    setState(() {
      userInfo = res;
    });
  }

  /// 注册事件监听
  regiterEventBus() {
    // 监听 GetUserInfoEvent 事件
    eventBus.on<GetUserInfoEvent>().listen((event) {
      // 刷新个人信息数据
      _getUserInfo();
    });
  }

  @override
  void initState() {
    super.initState();
    _getUserInfo();
    // 注册事件监听
    regiterEventBus();
  }

  /// 退出登录
  _logout() {
    // 弹窗进行二次确认
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('温馨提醒'),
        content: const Text('确定退出登录吗？'),
        actions: [
          TextButton(
            onPressed: () {
              // 关闭弹窗
              Navigator.pop(context);
            },
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () {
              // 关闭弹窗
              Navigator.pop(context);
              // 清空 token
              tokenManager.deleteToken();
              // 跳转首页(让 tabs 的索引值变成0) -> 可通过子传父实现
              widget.updateIndexFn(0);
            },
            child: const Text('确定'),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xC75591AF),
      //页面标题
      appBar: AppBar(
        title: const Text(
          '个人信息',
          style: TextStyle(color: Colors.white),
        ),
        backgroundColor: Colors.transparent,
        centerTitle: true,
      ),
      body: ListView(
        children: [
          // 个人信息
          Container(
            padding: const EdgeInsets.all(10),
            child: GestureDetector(
              onTap: () {
                // 跳转个人信息页，并传递用户信息
                Navigator.pushNamed(context, '/profile', arguments: userInfo);
              },
              // 个人信息
              child: Row(
                children: [
                  // 个人头像
                  ClipRRect(
                    borderRadius: BorderRadius.circular(50.0),
                    child: userInfo['avatar'] != null
                        ? Image.network(
                            userInfo['avatar'], // 网络图片
                            width: 50,
                            height: 50,
                          )
                        : Image.asset(
                            'assets/images/avatar_1.jpg', // 本地图片
                            width: 50,
                            height: 50,
                          ),
                  ),
                  const SizedBox(width: 10),
                  Text(
                    userInfo['nickName'] ?? '游客',
                    style: const TextStyle(fontSize: 16, color: Colors.white),
                  ),
                  const Spacer(),
                  const Text(
                    '去完善信息',
                    style: TextStyle(color: Colors.white),
                  ),
                  const Icon(
                    Icons.arrow_forward_ios,
                    color: Colors.white,
                    size: 13,
                  )
                ],
              ),
            ),
          ),
          // 我的房屋等工具栏
          Container(
            padding: const EdgeInsets.all(15),
            margin: const EdgeInsets.symmetric(
              vertical: 20,
              horizontal: 10,
            ),
            // 我的房屋等tab栏外边框装饰
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(10),
            ),
            child: Column(
              children: menuList
                  .map(
                    (item) => SizedBox(
                      height: 50,
                      child: GestureDetector(
                        onTap: () {
                          if (item["title"] == '我的房屋') {
                            Navigator.pushNamed(context, "/house");
                          }
                        },
                        child: Row(
                          children: [
                            Row(
                              children: [
                                Image.asset(
                                  item['icon'],
                                  width: 20,
                                  height: 20,
                                ),
                                const SizedBox(
                                  width: 10,
                                ),
                                Text(
                                  item['title'],
                                  style: const TextStyle(fontSize: 16),
                                )
                              ],
                            ),
                            const Spacer(),
                            const Icon(
                              Icons.arrow_forward_ios,
                              size: 12,
                              color: Colors.grey,
                            )
                          ],
                        ),
                      ),
                    ),
                  )
                  .toList(),
            ),
          ),
          // 退出登录
          Padding(
            padding: const EdgeInsets.all(10),
            child: ElevatedButton(
              onPressed: () {
                // 退出登录
                _logout();
              },
              child: const Text('退出登录'),
            ),
          )
        ],
      ),
    );
  }
}
